<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fns" uri="http://java.sun.com/jsp/jstl/functionss" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Home - BioCode</title>
    <style>


        table.draggable:hover {
            background-color: #f7dfe8;
        }

        table.draggable input[type=text], table.draggable select {
            width: 100%;
            font-size: 11px;
        }

        table.draggable:first-of-type {
            margin-top: 0;
        }

        table.draggable tr {
            height: 30px;
        }

        table.draggable {
            cursor: grab;
            cursor: -webkit-grab;
            width: 100%;
            border: 1px dotted #0fbad6;
            margin: 8px 0;
        }

        table.draggable td.remove-table-td {
            padding-right: 0;
            border-right: 1px dotted #0fbad6;
        }

        table.draggable td {
            padding-right: 10px;
        }

        td, th {
            padding: 0;
        }


    </style>

</head>
<body>
<div id="main">
    <c:if test="${null!=tool}">
        <div id="tool-header">
            <div class="row content-container" style="padding-bottom: 0">
                <div class="col-md-12">
                    <h1 class="tool-title"><a href="${host}/tools/${tool.id}">${tool.name}</a>
                        <small>${tool.desc}</small>
                    </h1>
                </div>
            </div>
            <ul class="nav nav-tabs" id="tool-nav-tab">
                <li><a href="${host}/tools/${tool.id}/show"><i class="fa fa-home"></i> Home</a></li>
                <li><a href="${host}/tools/${tool.id}/manual"><i class="fa fa-book"></i> Manual</a></li>
                <li><a href="${host}/tools/${tool.id}/releases"><i class="fa fa-download"></i> Downloads</a></li>
                <li><a href="${host}/tools/${tool.id}/stat"><i class="fa fa-bar-chart"></i> Statistics</a></li>
            </ul>
        </div>
    </c:if>
    <div class="content-container">
        <form class="tool_edit_form" id="new_tool" action="${host}/tools/save" accept-charset="UTF-8" method="post">

            <div class="row">
                <input type="hidden" name="id" value="${tool.id}">
                <div class="col-md-4" id="drag">
                    <div class="form-group">
                        <label for="tool_name">Name</label>
                        <input class="form-control" placeholder="Tool name" data-rule="required" type="text" name="name"
                               id="tool_name" value="${tool.name}">
                    </div>
                    <div class="form-group">
                        <label for="tool_desc">Description</label>
                        <input class="form-control" placeholder="Short description" data-rule="required" type="text"
                               name="desc" id="tool_desc" value="${tool.desc}">
                    </div>
                    <div class="form-group">
                        <label for="tool_website">Website</label>
                        <input class="form-control" placeholder="http://example.com" type="text" name="website"
                               id="tool_website" value="${tool.website}">
                    </div>
                    <div class="form-group">
                        <label for="tool_tech_ids">Technologies</label>
                        <select class="select2 form-control" multiple="" name="teches[][id]" id="tool_tech_ids"
                                tabindex="-1" aria-hidden="true">
                            <c:forEach items="${teches}" var="item">
                                <option value="${item.id}"
                                        <c:if test="${fn:contains(tool.teches, item)}">selected="selected"</c:if>>${item.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="tool_platform_ids">Platforms</label>

                        <select class="select2 form-control" multiple="" name="platforms[][id]" id="tool_platform_ids"
                                tabindex="-1" aria-hidden="true">
                            <c:forEach items="${platforms}" var="item">
                                <option value="${item.id}"
                                        <c:if test="${fn:contains(tool.platforms, item)}">selected="selected"</c:if>>${item.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="tool_user_interface_ids">User Interfaces</label>
                        <select class="select2 form-control" multiple="" name="userInterfaces[][id]"
                                id="tool_user_interface_ids" tabindex="-1" aria-hidden="true">
                            <c:forEach items="${userInterfaces}" var="item">
                                <option value="${item.id}"
                                        <c:if test="${fn:contains(tool.userInterfaces, item)}">selected="selected"</c:if>>${item.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="tool_tool_type_id">Tool Type</label>
                        <select class="select2 form-control" name="toolType[id]" id="tool_tool_type_id" tabindex="-1"
                                aria-hidden="true">
                            <c:forEach items="${toolTypes}" var="item">
                                <option value="${item.id}"
                                        <c:if test="${tool.toolType==item}">selected="selected"</c:if>>${item.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="tool_input_data_type_ids">Input Data Types</label>
                        <select class="select2 form-control" multiple="" name="dataTypes[][id]"
                                id="tool_input_data_type_ids" tabindex="-1" aria-hidden="true">
                            <c:forEach items="${dataTypes}" var="item">
                                <option value="${item.id}"
                                        <c:if test="${fn:contains(tool.dataTypes, item)}">selected="selected"</c:if>>${item.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="tool_category_ids">Categories</label>
                        <select class="select2 form-control" multiple="" name="categories[][id]" id="tool_category_ids"
                                tabindex="-1" aria-hidden="true">
                            <c:forEach items="${categoryTrees}" var="categoryTree">
                                <optgroup label="${categoryTree.root.name}">
                                    <c:forEach items="${categoryTree.leaves}" var="category">
                                        <option value="${category.id}"
                                                <c:if test="${fn:contains(tool.categories, category)}">selected="selected"</c:if>>${category.name}</option>
                                    </c:forEach>
                                </optgroup>
                            </c:forEach>


                        </select>
                    </div>
                    <button class="btn btn-primary" type="submit" id="save">Save</button>
                </div>
                <div class="col-md-8">
                    <div class="form-group">
                        <label for="tool_introduction">Introduction</label>
                        <textarea class="tinymce" rows="10" name="introduction" id="tool_introduction"
                                  aria-hidden="true">${tool.introduction}</textarea>
                    </div>
                    <div class="form-group">

                        <label>Publications</label>
                        <button class="btn-link pull-right add_el_from_tpl" data-target="publicationList"
                                data-template="tpl_publication" type="button">
                            <i class="fa fa-plus"></i>
                        </button>

                        <div class="draggable-container" id="publicationList">
                            <c:if test="${fn:length(tool.publicationList) > 0}">
                                <c:forEach items="${tool.publicationList}" var="publication">
                                    <table class="draggable publication">
                                        <tbody>
                                        <tr>
                                            <td class="remove-table-td" rowspan="5" width="18px">
                                                <button aria-label="Delete this publication"
                                                        class="remove-table hint-left btn-link" type="button">
                                                    <i class="fa fa-times"></i>
                                                </button>
                                            </td>
                                            <th width="55px">DOI</th>
                                            <td colspan="3" width="300px">
                                                <input name="publicationList[][doi]" style="width: 150px" type="text"
                                                       value="${publication.doi}"/>
                                                <button aria-label="Auto fill with DOI"
                                                        class="publication_search hint--info hint--right btn-link"
                                                        type="button">
                                                    <i class="fa fa-search fa-fw"></i>
                                                </button>
                                            </td>
                                            <th width="55px">PMID</th>
                                            <td colspan="4" width="200px">
                                                <input name="publicationList[][pmid]" style="width: 100px" type="text"
                                                       value="${publication.pmid}"/>
                                                <button aria-label="Auto fill with Pubmed ID"
                                                        class="pmid_search hint--info hint--right btn-link"
                                                        type="button">
                                                    <i class="fa fa-search fa-fw"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Journal</th>
                                            <td width="200px">
                                                <input name="publicationList[][journal]" type="text"
                                                       value="${publication.journal}"/>
                                            </td>
                                            <th>Issue</th>
                                            <td>
                                                <input name="publicationList[][issue]" type="text"
                                                       value="${publication.issue}"/>
                                            </td>
                                            <th>Volume</th>
                                            <td>
                                                <input name="publicationList[][volume]" type="text"
                                                       value="${publication.volume}"/>
                                            </td>
                                            <th width="50px">Date</th>
                                            <td>
                                                <input name="publicationList[][date]" type="text"
                                                       value="${publication.date}"/>
                                            </td>
                                            <td></td>
                                        </tr>
                                        <tr>
                                            <th>Title</th>
                                            <td colspan="8">
                                                <input name="publicationList[][title]" type="text"
                                                       value="${publication.title}"/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Authors</th>
                                            <td colspan="8">
                                                <input name="publicationList[][authors]" type="text"
                                                       value="${publication.authors}"/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>
                                        <span aria-label="Citations by Google Scholar "
                                              class="hint--bottom">Citations</span>
                                            </th>
                                            <td>
                                                <input name="publicationList[][citation]" type="text"
                                                       value="${publication.citation}"/>
                                            </td>
                                            <th colspan="7" style="text-align: right;padding-right:10px">
                                            <span aria-label="Suggest users to cite this publication"
                                                  class="hint--bottom">Primary Publication</span>
                                                <input type="checkbox" name="publicationList[][citethis]"
                                                       value="true" <c:if
                                                        test="${publication.citethis}"> checked="checked"</c:if>/>
                                            </th>
                                        </tr>
                                        </tbody>
                                    </table>
                                </c:forEach>
                            </c:if>
                            <c:if test="${fn:length(tool.publicationList) ==0}">
                                <div class="empty-placeholder"><p>No publicationList attached</p></div>
                            </c:if>


                        </div>
                    </div>
                    <div class="form-group">
                        <label for="tool_fundings">Fundings</label>
                        <textarea rows="5" class="form-control" name="fundings"
                                  id="tool_fundings">${tool.fundings}</textarea>
                    </div>
                    <div class="form-group">
                        <label>Credits</label>
                        <button class="btn-link pull-right append-credit" data-target="credits"
                                data-template="tpl_credit" type="button">
                            <i class="fa fa-plus"></i>
                        </button>

                        <div class="draggable-container" id="credits">
                            <c:if test="${fn:length(tool.credits) > 0}">
                                <c:forEach items="${tool.credits}" var="credit">
                                <table class="draggable credit-editor">
                                    <%--<input type="hidden" name="id" value="${credit.id}">--%>
                                    <tbody>
                                    <tr>
                                        <td class="remove-table-td" rowspan="5" width="18px">
                                            <button aria-label="Remove this person"
                                                    class="remove-table hint-left btn-link"
                                                    type="button">
                                                <i class="fa fa-times"></i>
                                            </button>
                                        </td>
                                        <th width="100px">
                                            <div class="form-group">
                                                <label>Email</label>
                                            </div>
                                        </th>
                                        <td style="padding-top: 5px">
                                            <div class="form-group">
                                                <select name="credits[][user][email]"
                                                        class="form-control credit_email">
                                                    <option value='' selected='selected'></option>
                                                    <c:if test="${!empty credit.user.email}">
                                                        <option value="${credit.user.email}" selected>${credit.user.email}</option>
                                                    </c:if>
                                                </select>
                                            </div>
                                        </td>
                                        <th width="100px">
                                            <div class="form-group">
                                                <label>Full Name</label>
                                            </div>
                                        </th>
                                        <td style="padding-top: 5px" width="250px">
                                            <div class="form-group">
                                                <input class="form-control" name="credits[][user][fullName]"
                                                       placeholder="Input the Full Name" type="text" value="${credit.user.fullName}"/>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>
                                            <div class="form-group">
                                                <label>Roles</label>
                                            </div>
                                        </th>
                                        <td colspan="3">
                                            <div class="form-group">
                                                <select name="credits[][creditRoleList][][id]"
                                                        data-placeholder="Select the Roles" multiple="multiple"
                                                        class="form-control select2">
                                                    <c:forEach items="${roles}" var="role">
                                                        <option value="${role.id}" <c:if test="${fns:containsForList(credit.creditRoleList, role)}">selected="selected"</c:if>>${role.name}</option>
                                                    </c:forEach>
                                                </select>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>
                                            <div class="form-group">
                                                <label>Organization</label>
                                            </div>
                                        </th>
                                        <td colspan="3">
                                            <div class="form-group">
                                                <select name="credits[][organization][name]"
                                                        class="form-control">
                                                    <option value=""></option>
                                                    <c:if test="${!empty credit.organization}">
                                                        <option value="${credit.organization.name}" selected>${credit.organization.name}</option>
                                                    </c:if>
                                                </select>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>
                                            <div class="form-group">
                                                <label>Department</label>
                                            </div>
                                        </th>
                                        <td colspan="3">
                                            <div class="form-group">
                                                <select name="credits[][organization][department]"
                                                        class="form-control">
                                                    <option value=""></option>
                                                    <c:if test="${!empty credit.organization}">
                                                        <option value="${credit.organization.department}" selected>${credit.organization.department}</option>
                                                    </c:if>
                                                </select>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>
                                            <div class="form-group">
                                                <label>Country/Region</label>
                                            </div>
                                        </th>
                                        <td colspan="3">
                                            <div class="form-group">
                                                <select name="credits[][organization][country]"
                                                        data-placeholder="Select the Country/Region"
                                                        class="form-control select2">
                                                    <option value=""></option>
                                                    <c:forEach items="${countryList}" var="item">
                                                        <option value="${item.code}"
                                                                <c:if test="${fn:contains(credit.organization.country, item.code)}">selected="selected"</c:if>>${item.name}</option>
                                                    </c:forEach>

                                                </select>
                                            </div>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                                 </c:forEach>
                            </c:if>
                            <c:if test="${fn:length(tool.credits) ==0}">
                                <div class="empty-placeholder"><p>No credits attached</p></div>
                            </c:if>
                        </div>
                    </div>
                </div>
            </div>
   <%--         <input class="form-control" name="credits[][user]"
                   placeholder="Input the Full Name" type="text" value="wangfan1"/>
            <input class="form-control" name="credits[][user]"
                   placeholder="Input the Full Name" type="text" value="wangfan2"/>--%>

        </form>
        <script id="tpl_publication" type="text/html">
            <table class="draggable publication">
                <tbody>
                <tr>
                    <td class="remove-table-td" rowspan="6" width="20px">
                        <button aria-label="Delete this publication" class="remove-table hint-left btn-link"
                                type="button">
                            <i class="fa fa-times"></i>
                        </button>
                    </td>
                    <th width="55px">DOI</th>
                    <td colspan="3" width="300px">
                        <input name="publicationList[][doi]" style="width: 150px" type="text"/>
                        <button aria-label="Auto fill with DOI"
                                class="publication_search hint--info hint--right btn-link" type="button">
                            <i class="fa fa-search fa-fw"></i>
                        </button>
                    </td>
                    <th width="55px">PMID</th>
                    <td colspan="4" width="180px">
                        <input name="publicationList[][pmid]" style="width: 100px" type="text"/>
                        <button aria-label="Auto fill with Pubmed ID"
                                class="pmid_search hint--info hint--right btn-link" type="button">
                            <i class="fa fa-search fa-fw"></i>
                        </button>
                    </td>
                </tr>
                <tr>
                    <th>Journal</th>
                    <td width="160px">
                        <input name="publicationList[][journal]" type="text"/>
                    </td>
                    <th>Issue</th>
                    <td width="100px">
                        <input name="publicationList[][issue]" type="text"/>
                    </td>
                    <th>Volume</th>
                    <td width="100px">
                        <input name="publicationList[][volume]" type="text"/>
                    </td>
                    <th width="40px">Date</th>
                    <td width="100px">
                        <input name="publicationList[][date]" type="text" width="40px"/>
                    </td>
                    <td></td>
                </tr>
                <tr>
                    <th>Title</th>
                    <td colspan="8">
                        <input name="publicationList[][title]" type="text"/>
                    </td>
                </tr>
                <tr>
                    <th>Authors</th>
                    <td colspan="8">
                        <input name="publicationList[][authors]" type="text"/>
                    </td>
                </tr>
                <tr>
                    <th>
                        <span aria-label="Citations by Google Scholar " class="hint--bottom">Citations</span>
                    </th>
                    <td>
                        <input name="publicationList[][citation]" type="text"/>
                    </td>
                    <th colspan="7" style="text-align: right;padding-right:10px">
                        <span aria-label="Suggest users to cite this publication" class="hint--bottom">Primary Publication</span>
                        <input type="checkbox" name="publicationList[][citethis]"
                               value="true"/>
                    </th>
                </tr>
                </tbody>
            </table>


        </script>
        <script id="tpl_credit" type="text/html">
            <table class="draggable credit-editor">
                <tbody>
                <tr>
                    <td class="remove-table-td" rowspan="5" width="18px">
                        <button aria-label="Remove this person" class="remove-table hint-left btn-link"
                                type="button">
                            <i class="fa fa-times"></i>
                        </button>
                    </td>
                    <th width="100px">
                        <div class="form-group">
                            <label>Email</label>
                        </div>
                    </th>
                    <td style="padding-top: 5px">
                        <div class="form-group">
                            <select name="credits[][user][email]"
                                    class="form-control credit_email">
                                <option value='' selected='selected'></option>

                            </select>
                        </div>
                    </td>
                    <th width="100px">
                        <div class="form-group">
                            <label>Full Name</label>
                        </div>
                    </th>
                    <td style="padding-top: 5px" width="250px">
                        <div class="form-group">
                            <input class="form-control" name="credits[][user][fullName]"
                                   placeholder="Input the Full Name" type="text"/>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>
                        <div class="form-group">
                            <label>Roles</label>
                        </div>
                    </th>
                    <td colspan="3">
                        <div class="form-group">
                            <select name="credits[][creditRoleList][][id]" data-placeholder="Select the Roles"
                                    multiple="multiple"
                                    class="form-control select2">
                                <option value="1">Investigator</option>
                                <option value="2">Developer</option>
                                <option value="3">Contributor</option>
                            </select>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>
                        <div class="form-group">
                            <label>Organization</label>
                        </div>
                    </th>
                    <td colspan="3">
                        <div class="form-group">
                            <select name="credits[][organization][name]"
                                    class="form-control">
                                <option value=""></option>
                            </select>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>
                        <div class="form-group">
                            <label>Department</label>
                        </div>
                    </th>
                    <td colspan="3">
                        <div class="form-group">
                            <select name="credits[][organization][department]"
                                    class="form-control">
                                <option value=""></option>
                            </select>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>
                        <div class="form-group">
                            <label>Country/Region</label>
                        </div>
                    </th>
                    <td colspan="3">
                        <div class="form-group">
                            <select name="credits[][organization][country]" data-placeholder="Select the Country/Region"
                                    class="form-control select2">
                                <option value=""></option>
                                <c:forEach items="${countryList}" var="item">
                                    <option value="${item.code}"
                                            <c:if test="${fn:contains(currentUser.country, item.name)}">selected="selected"</c:if>>${item.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>
        </script>
    </div>
</div>
<script>
    var ue = UE.getEditor('tool_introduction', {
        initialFrameHeight: 300,
        initialFrameWeight: 100
    });
    $(document).ready(function () {
        dragula([document.getElementById('publicationList')]);
        dragula([document.getElementById('credits')]);
        init_credit_email_selector($('.credit-editor'));
        init_credit_org_name_selector($('.credit-editor'));
        init_credit_org_department_selector($('.credit-editor'));
        new SMValidator('form', {
            submit: function (valid, form) {
                if (valid) {
                    var formArray = $("#new_tool").serializeObject();
//                    var formArray = $("#new_tool").serializeForm();
//                    var formArray = $("#new_tool").serializeObject();
                    console.log(formArray);
                    $.ajax({
                        url: "${host}/tools/save",
                        type: 'POST',
                        datatype: "json",
                        contentType: "application/json",
                        data: JSON.stringify(formArray),
                        cache: false,
                        error: function (request) {
                            alert("发生错误");
                        },
                    }).done(function (result) {
                        //接收后台返回的结果
                        if (result.status == 0) {
                            alert("保存成功");
                            <%--location.href = "${host}/tools/" + result.data + "/show";--%>
                        }


                    });
                } else {
                    alert("error");
                }

            }
        });

        $('.append-credit').click(function () {

            $target = add_el_from_tpl(this);
            init_credit_email_selector($target);
            init_credit_org_name_selector($target);
            init_credit_org_department_selector($target)
        })
        $('.add_el_from_tpl').click(function () {

            add_el_from_tpl(this)
        })

    });

    function add_el_from_tpl(btn) {
        var template = $(btn).data('template');
        var target = $(btn).data('target');
        $("#" + target).find('.empty-placeholder').hide()
        var templateHtml = $("#" + template).text();
        $("#" + target).append(templateHtml);
        console.log($("#" + target).find('table:last .select2'));
        $("#" + target).find('table:last .select2').select2();
        return $("#" + target);

    }


    $(document).on('click', '.pmid_search', function (e) {
        e.preventDefault();
        $table = $(this).closest('table.publication');
        pmid = $table.find('input[name="publicationList[][pmid]"]').val()
        if (!pmid) {
            return false;
        }
        $i = $(this).find('i')
        $i.attr('class', 'fa fa-spinner fa-spin fa-fw')
        $.ajax({
            url: "${host}/api/pmidSearch",
            data: {
                pmid: pmid
            },
            method: 'get',
            success: function (result) {
                if (result.status == 0) {


                    var p = result.data;

                    $table.find('input[name="publicationList[][title]"]').val(p.title)
                    $table.find('input[name="publicationList[][authors]"]').val(p.authors)
                    $table.find('input[name="publicationList[][journal]"]').val(p.journal)
                    $table.find('input[name="publicationList[][date]"]').val(p.date)
                    $table.find('input[name="publicationList[][issue]"]').val(p.issue)
                    $table.find('input[name="publicationList[][volume]"]').val(p.volume)
                    $table.find('input[name="publicationList[][doi]"]').val(p.doi)
                    $table.find('input[name="publicationList[][pmid]"]').val(p.pmid)
                    $table.find('input[name="publicationList[][citation]"]').val(p.citation)
                }


            },
            complete: function () {
                $i.attr('class', 'fa fa-search fa-fw')
            }

        })


    });


    $(document).on('click', '.publication_search', function (e) {
        e.preventDefault();
        $table = $(this).closest('table.publication');
        doi = $table.find('input[name="publicationList[][doi]"]').val()
        if (!doi) {
            return false;
        }
        $i = $(this).find('i')
        $i.attr('class', 'fa fa-spinner fa-spin fa-fw')
        $.ajax({
            url: "${host}/api/doiSearch",
            data: {
                doi: doi
            },
            method: 'get',
            success: function (result) {
                if (result.status == 0) {
                    var p = result.data;
                    $table.find('input[name="publicationList[][title]"]').val(p.title)
                    $table.find('input[name="publicationList[][authors]"]').val(p.authors)
                    $table.find('input[name="publicationList[][journal]"]').val(p.journal)
                    $table.find('input[name="publicationList[][date]"]').val(p.date)
                    $table.find('input[name="publicationList[][issue]"]').val(p.issue)
                    $table.find('input[name="publicationList[][volume]"]').val(p.volume)
                    $table.find('input[name="publicationList[][doi]"]').val(p.doi)
                    $table.find('input[name="publicationList[][pmid]"]').val(p.pmid)
                    $table.find('input[name="publicationList[][citation]"]').val(p.citation)
                }


            },
            complete: function () {
                $i.attr('class', 'fa fa-search fa-fw')
            }

        })


    });

    function credit_email_change(selector) {
        data = $(selector).select2('data')[0];
        fullname = data.full_name;
        $ptable = $(selector).parents('table')
        el_fullname = $ptable.find('input[name="credits[][user][fullName]"]');
        if (fullname) {
            el_fullname.val(fullname);
            el_fullname.attr('readonly', 'readonly');
//            $ptable.find('select[name="credits[][org_name]"]').val(data.org_name).trigger 'change'
//            $ptable.find('select[name="credits[][country]"]').val(data.org_country).trigger 'change'


        } else {
            el_fullname.val("");
            el_fullname.removeAttr('readonly');
        }


    }


    function init_credit_email_selector($parent) {
        $credit_email_selector = $parent.find('select[name="credits[][user][email]"]');
        $credit_email_selector.select2({
            placeholder: 'Select or input the email',
            tags: true,
            minimumInputLength: 2,
            ajax: {
                url: "${host}/api/emails",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term,
                        page: params.page
                    };
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (user, i) {
                            var text = user.email;
                            var name = user.fullName ? (" (" + user.fullName + ")") : "";
                            return {
                                id: user.email,
                                text: text + name,
                                full_name: user.fullName
                            };
                        })
                    };
                },
                cache: true
            }
        }).on("select2:select", function () {
            credit_email_change(this);
        });
    }


    function org_name_change(selector) {
        data = $(selector).select2('data')[0];
        name = data.id;
        $ptable = $(selector).parents('table')
        el_department = $ptable.find('select[name="credits[][organization][department]"]');
        if (name) {

            $.ajax({
                type: "GET",
                url: "${host}/api/departments",
                data: {
                    name: name
                },
                dataType: "json",
                success: function (res) {
                    el_department.select2('destroy');
                    el_department.empty();

                    el_department.select2({
                        tags: true,
                        data: $.map(res, function (org, i) {
                            return {
                                id: org.department,
                                text: org.department,
                                country: org.country
                            };
                        })
                    }).on("select2:select", function () {
                        org_department_change(this);
                    });
                    ;
                }
            });


        } else {
            el_fullname.removeAttr('readonly');
        }


    }

    function org_department_change(selector) {
        data = $(selector).select2('data')[0];
        country = data.country;
        $ptable = $(selector).parents('table')
        el_country = $ptable.find('select[name="credits[][organization][country]"]');
        if (country) {
            el_country.val(country);
            el_country.trigger("change");
            el_country.select2("readonly", true);
        } else {
            el_country.removeAttr('readonly');
        }


    }


    function init_credit_org_name_selector($parent) {
        $org_name_selector = $parent.find('select[name="credits[][organization][name]"]');
        $org_name_selector.select2({
            placeholder: 'Select or input the organization name',
            tags: true,
            minimumInputLength: 2,
            ajax: {
                url: "${host}/api/organizations",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term,
                        page: params.page
                    };
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (organization, i) {
                            return {
                                id: organization.name,
                                text: organization.name
                            };
                        })
                    };
                },
                cache: true
            }
        }).on("select2:select", function () {
            org_name_change(this);
        });
    }

    function init_credit_org_department_selector($parent) {
        $org_name_selector = $parent.find('select[name="credits[][organization][department]"]');
        $org_name_selector.select2({
            placeholder: 'Select or input the department name',
            tags: true

        }).on("select2:select", function () {
            org_department_change(this);
        });
    }


    $(document).on('click', '.remove-table', function () {
        $(this).closest('table').fadeOut(function () {
            $(this).remove();
        });
    });


</script>
</body>

</html>
